package com.edee.bigday.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class LoginController {
    @Autowired
    StringRedisTemplate redisTemplate;

    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("token") String token) {
        String s = redisTemplate.opsForValue().get(token);
        return s;
    }

    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String url, Model model,
                            @CookieValue(value = "sso_token", required = false) String sso_token) {
        //上面利用SpringMVC轻松获取cookie：@CookieValue(value = "sso_token", required = false) String sso_token
        if (!StringUtils.isEmpty(sso_token)) {
            //说明此前已有用户在某个系统登录过（留下了登录痕迹），重定向到登录前用户所访问的页面：
            return "redirect:" + url + "?token=" + sso_token;
        }
        model.addAttribute("url", url);
        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(String username, String password, String url, HttpServletResponse response) {
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            //简单处理为：只要用户名、密码都不为空，即为登录成功，将登录成功的用户信息保存到Redis中
            String uuid = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(uuid, username);
            //在响应数据中保存cookie：
            Cookie sso_token = new Cookie("sso_token", uuid);
            response.addCookie(sso_token);
            // 跳回至登录前的页面：
            return "redirect:" + url + "?token=" + uuid;
        }
        //登录失败，跳转至登录页：
        return "login";
    }
}
